package com.hfzy.ihk.web.aliyuncall.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.uuid.base64uuid.UUIDs;
import com.hfzy.ihk.facade.aliyuncall.enums.AsrActionEnum;
import com.hfzy.ihk.facade.aliyuncall.enums.CallTypeEnum;
import com.hfzy.ihk.facade.aliyuncall.enums.MsgTypeEnum;
import com.hfzy.ihk.web.aliyuncall.vo.AliyunAsrResponeVo;
import com.hfzy.ihk.web.aliyuncall.vo.AnalysisAsrResponeVo;
import com.hfzy.ihk.web.aliyuncall.vo.AsrWordVo;
import com.hfzy.ihk.web.aliyuncall.vo.VoiceRTASRReportVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ASR智能外呼具体操作业务类
 */
@Component
public class AliyunAsrOptBiz {


    private static final Logger logger = LoggerFactory.getLogger(AliyunAsrOptBiz.class);
    @Autowired
    PushDataToBrowserBiz pushDataToBrowserBiz;

    @Autowired
    PushDataToAnalysis pushDataToAnalysis;
    /**
     * 通过实时语音得到当前需要操作命令
     * @param content
     * @param callId 业务id
     * @param contentType 消息类型normal、mute(静音)
     * @return
     */
    public AliyunAsrResponeVo AsrOpt(String content,String callId,String contentType){
        Long dealStartTime = System.currentTimeMillis();
        AliyunAsrResponeVo aliyunAsrResponeVo = new AliyunAsrResponeVo();
        aliyunAsrResponeVo.setResult("success");
        aliyunAsrResponeVo.setCode(200);
        aliyunAsrResponeVo.setMsg("成功");

        AliyunAsrResponeVo.Data data = new AliyunAsrResponeVo.Data();
        AsrWordVo asrWordVo = JSON.parseObject(content, AsrWordVo.class);
        try {
            //推送分析服务器和浏览器并返回结果
            AnalysisAsrResponeVo analysisAsrResponeVo = this.pushData(contentType,content);
            if(StringTools.isNotempty(analysisAsrResponeVo)){

                if(AsrActionEnum.PLAY.getValue().equals(analysisAsrResponeVo.getAction())) {
                    //有录音就用录音，没有录音用语音识别
                    data.setAction(AsrActionEnum.PLAY.getValue());
                    data.setAction_code("$name$");
                    Map<String, String> map = new HashMap<>();
                    map.put("name", analysisAsrResponeVo.getSpeaking());
                    data.setAction_code_param(JSON.toJSONString(map));
                    if (StringTools.isNotempty(analysisAsrResponeVo.getActionCodeBreak())) {
                        data.setAction_code_break(analysisAsrResponeVo.getActionCodeBreak());
                    }
                }else{
                    data.setAction(analysisAsrResponeVo.getAction());
                }
            }else{
                data.setAction(AsrActionEnum.BREAK.getValue());
            }
        }catch (Exception e){
            logger.error("--------------->处理Asr 实时翻译消息异常:{}",content,e);
        }finally {
            data.setCall_id(callId);
            data.setDynamic_id(asrWordVo.getDynamic_id());
            aliyunAsrResponeVo.setData(data);
            logger.info("---------------->返回的asr 回调返回:{},业务处理时间：{}",JSON.toJSONString(aliyunAsrResponeVo),(System.currentTimeMillis()-dealStartTime));
            return aliyunAsrResponeVo;
        }


    }


//                if (StringTools.isNotempty(content)) {
//        if ("normal".equals(contentType)) { //识别的普通消息
//            //推送识别的消息去前端
//            VoiceRTASRReportVo voiceRTASRReportVo = new VoiceRTASRReportVo();
//            voiceRTASRReportVo.setWordId(UUIDs.base64UUID());
//            voiceRTASRReportVo.setWords(asrWordVo.getWords());
//            voiceRTASRReportVo.setRole("A");
//            voiceRTASRReportVo.setOut_id(asrWordVo.getDynamic_id());
//            voiceRTASRReportVo.setEnd_offset(asrWordVo.getEnd_offset());
//            voiceRTASRReportVo.setBegin_offset(asrWordVo.getBegin_offset());
//            //将消息推送到浏览器
//            pushDataToBrowserBiz.pushAsrToBrowser(voiceRTASRReportVo, CallTypeEnum.ASR_CALL.getValue()); //异步
//
//            //推送识别的消息去分析服务器
//            //推送识别结果去分析服务器 并且返回下一步操作指令，这里必须同步实现
//            String[] arg = pushDataToAnalysis.readPackageIdAndCallTaskId(voiceRTASRReportVo.getOut_id());
//            //判断如果是保利测试生成的数据则不进行推送
//            if(arg!=null&&arg.length>=2){
//                logger.info("---->packageId:{},callTaskId：{},",arg[0],arg[1]);
//                String rs = pushDataToAnalysis.pushAsrData(arg[0],arg[1],voiceRTASRReportVo.getOut_id(),voiceRTASRReportVo,CallTypeEnum.ASR_CALL.getValue(), MsgTypeEnum.NORMAL.getValue());
//                logger.info("------>分析服务器返回的结果：{}",rs);
//                if(StringTools.isNotempty(rs)){
//                    AnalysisAsrResponeVo analysisAsrResponeVo = JSON.parseObject(rs, AnalysisAsrResponeVo.class);
//                    if(StringTools.isNotempty(analysisAsrResponeVo.getSpeaking())) {
//                        //有录音就用录音，没有录音用语音识别
//                        data.setAction(AsrActionEnum.PLAY.getValue());
//                        data.setAction_code("$name$");
//                        Map<String, String> map = new HashMap<>();
//                        map.put("name", analysisAsrResponeVo.getSpeaking());
//                        data.setAction_code_param(JSON.toJSONString(map));
//                        if(StringTools.isNotempty(analysisAsrResponeVo.getActionCodeBreak())){
//                            data.setAction_break(analysisAsrResponeVo.getActionCodeBreak());
//                        }
////                            if(StringTools.isNotempty(analysisAsrResponeVo.getActionCodeBreak())&&StringTools.isNotempty(analysisAsrResponeVo.getRecordCodeNum())) {
////                                data.setAction(AsrActionEnum.PLAY.getValue());
////                                data.setAction_code(analysisAsrResponeVo.getRecordCodeNum());
////                                data.setAction_break(analysisAsrResponeVo.getActionCodeBreak());
////                            }else{
////                                data.setAction(AsrActionEnum.PLAY.getValue());
////                                data.setAction_code("$name$");
////                                Map<String,String> map = new HashMap<>();
////                                map.put("name",analysisAsrResponeVo.getSpeaking());
////                                data.setAction_code_param(JSON.toJSONString(map));
////                            }
//                    }else{
//                        data.setAction(AsrActionEnum.BREAK.getValue());
//                    }
//                }else{
//                    data.setAction(AsrActionEnum.BREAK.getValue());
//                }
//            }
//        }else if("mute".equals(contentType)){//静音消息
//            String[] arg = pushDataToAnalysis.readPackageIdAndCallTaskId(asrWordVo.getDynamic_id());
//            VoiceRTASRReportVo voiceRTASRReportVo = new VoiceRTASRReportVo();
//            voiceRTASRReportVo.setWordId(UUIDs.base64UUID());
//            voiceRTASRReportVo.setOut_id(asrWordVo.getDynamic_id());
//            String rs = pushDataToAnalysis.pushAsrData(arg[0],arg[1],asrWordVo.getDynamic_id(),voiceRTASRReportVo,CallTypeEnum.ASR_CALL.getValue(),MsgTypeEnum.MUTE.getValue());
//        }
//    }

    /**
     * 推送
     * @param contentType
     * @param content
     * @return
     */
    public AnalysisAsrResponeVo pushData(String contentType,String content){
        String rs = null;
        AnalysisAsrResponeVo analysisAsrResponeVo = null;
        try{
            if (StringTools.isNotempty(content)) {
                AliyunAsrResponeVo.Data data = new AliyunAsrResponeVo.Data();
                AsrWordVo asrWordVo = JSON.parseObject(content, AsrWordVo.class);

                //获取包id 和 任务id
                String[] arg = pushDataToAnalysis.readPackageIdAndCallTaskId(asrWordVo.getDynamic_id());
                if(arg==null||arg.length<2){ //不符合返回
                    return null;
                }

                VoiceRTASRReportVo voiceRTASRReportVo = new VoiceRTASRReportVo();
                voiceRTASRReportVo.setWordId(UUIDs.base64UUID());
                voiceRTASRReportVo.setOut_id(asrWordVo.getDynamic_id());
                if ("normal".equals(contentType)) { //识别的普通消息
                    voiceRTASRReportVo.setWords(asrWordVo.getWords());
                    voiceRTASRReportVo.setRole("A");
                    //将消息推送到浏览器
                    pushDataToBrowserBiz.pushAsrToBrowser(voiceRTASRReportVo, CallTypeEnum.ASR_CALL.getValue()); //异步

                    voiceRTASRReportVo.setEnd_offset(asrWordVo.getEnd_offset());
                    voiceRTASRReportVo.setBegin_offset(asrWordVo.getBegin_offset());
                    //推送到分析服务器 异步
                    rs= pushDataToAnalysis.pushAsrData(arg[0],arg[1],voiceRTASRReportVo.getOut_id(),voiceRTASRReportVo,CallTypeEnum.ASR_CALL.getValue(), MsgTypeEnum.NORMAL.getValue());
                } else if ("mute".equals(contentType)) {
                    voiceRTASRReportVo.setWordId(UUIDs.base64UUID());
                    voiceRTASRReportVo.setOut_id(asrWordVo.getDynamic_id());
                    //推送识别结果去分析服务器 并且返回下一步操作指令，这里必须同步实现
                    rs = pushDataToAnalysis.pushAsrData(arg[0],arg[1],asrWordVo.getDynamic_id(),voiceRTASRReportVo,CallTypeEnum.ASR_CALL.getValue(),MsgTypeEnum.MUTE.getValue());
                } else {
                    logger.info(">>>>>>>>>>ars 回调获取到无法识别消息类型：{}",contentType);
                }

                if(rs==null){
                    return null;
                }
                //不为空返回处理结果
                analysisAsrResponeVo = JSON.parseObject(rs, AnalysisAsrResponeVo.class);
            }
        }catch (Exception e){
            logger.error(">>>>>>>>>>>.asr 推送数据到分析服务器异常~",e);
            e.printStackTrace();
        }
        return analysisAsrResponeVo;
    }









}
